﻿
Imports System.Configuration

Imports Moca.Db
Imports Moca.Win

Public Class EntityCodeGeneratorForm

	Private _dt As DataTable

	Private _dbc As DbContextProperty

	Private Sub EntityCodeGeneratorForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		_dbc = Nothing
		Me.DataGridView1.AllowUserToAddRows = False
		Me.DataGridView1.AllowUserToDeleteRows = False
		Me.DataGridView1.ReadOnly = True
		Me.btnGenerate.Enabled = False

		_setCboConnectionStrings()

        Me.RichTextBox1.Focus()
		Me.Label2.Text = "Select the connection , please execute the SQL statement. And please to generate the code."

#If DEBUG Then
		Me.RichTextBox1.Text = "select * from tbDemoEntities"
#End If
	End Sub

	Private Sub btnSQL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSQL.Click
		If _dbc Is Nothing Then
			WinUtil.DispMessageBox("Select DbContext", WinUtil.MessageBoxType.CriticalOK, String.Empty)
			Me.cboConnectionStrings.Focus()
			Exit Sub
		End If
		If Me.RichTextBox1.Text.Length = 0 Then
			WinUtil.DispMessageBox("Input SQL", WinUtil.MessageBoxType.CriticalOK, String.Empty)
			Me.RichTextBox1.Focus()
			Exit Sub
		End If

		Me.btnGenerate.Enabled = False

		Dim dt As DataTable

		Try
			Dim dao As Db.Impl.DaoGetter
			Dim dbmsWk As Dbms

			dbmsWk = New Dbms(_dbc.Name, _dbc.ProviderName, _dbc.ConnectionString)

			dao = New Db.Impl.DaoGetter(dbmsWk)

			dt = dao.Go(Me.RichTextBox1.Text)

			Me.DataGridView1.DataSource = dt

			_dt = dt
			setGenerate()
		Catch ex As Exception
			WinUtil.DispMessageBox(ex.Message, WinUtil.MessageBoxType.CriticalOK, String.Empty)
		End Try
	End Sub

	Private Sub btnOptions_Click(sender As System.Object, e As System.EventArgs) Handles btnOptions.Click
		Using frm As Form = New OptionDialog
			frm.ShowDialog(Me)
		End Using
		_setCboConnectionStrings()
	End Sub

	Private Sub PropertyGrid1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PropertyGrid1.Leave
		My.Settings.Save()
	End Sub

	Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
		' Ctrl + Enter をボタンのショートカットキーとして処理する
		If keyData = Keys.Control + Keys.Enter Then
			Me.btnSQL.PerformClick()
			Return True
		End If
		' Ctrl + S をボタンのショートカットキーとして処理する
		If keyData = Keys.Control + Keys.S Then
			Me.btnGenerate.PerformClick()
			Return True
		End If
		' Ctrl + O をボタンのショートカットキーとして処理する
		If keyData = Keys.Control + Keys.O Then
			Me.btnOptions.PerformClick()
			Return True
		End If

		Return MyBase.ProcessCmdKey(msg, keyData)
	End Function

	''' <summary>
	''' DB接続可能かチェックする
	''' </summary>
	''' <remarks></remarks>
	Protected Sub canConnectDb()
		Using dao = New Db.Impl.DaoGetter(Me.cboConnectionStrings.SelectedText)
			Try
				dao.Connection.Open()
			Catch ex As Exception
				WinUtil.DispMessageBox("Not connected to the database." & vbCrLf & "Please set it with a Configuration dialog again.", WinUtil.MessageBoxType.CriticalOK, "")
			End Try
		End Using
	End Sub

	Private Sub setGenerate()
		Me.btnGenerate.Enabled = True
		Me.DataGridView2.AllowUserToAddRows = False

        Dim dt As DataTable

		dt = New DataTable("")
		dt.Columns.Add("ColumnName")
		'dt.Columns.Add("TableName")

		For Each col As DataColumn In _dt.Columns
			Dim row As DataRow = dt.NewRow()
			dt.Rows.Add(row)
			row.Item(0) = col.ColumnName
			'row.Item(1) = col.Table.TableName
		Next

        Me.DataGridView2.DataSource = dt

        Me.txtClassName.Focus()
	End Sub

	Private Sub _setCboConnectionStrings()
		Dim lst As ArrayList
		Dim g As Graphics = Me.cboConnectionStrings.CreateGraphics()
		Dim f As Font = Me.cboConnectionStrings.Font
		Dim max As Single = Me.cboConnectionStrings.Width

		lst = New ArrayList
		For Each key As DbContextProperty In My.MySettings.Default.DbContext
			Dim nm As String = key.Name
			lst.Add(nm)
			max = Math.Max(max, g.MeasureString(nm, f).Width)
		Next

		Me.cboConnectionStrings.BeginUpdate()
		Me.cboConnectionStrings.DataSource = lst
		Me.cboConnectionStrings.EndUpdate()
	End Sub



	Private Sub btnGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerate.Click
		If _dbc.OutputFolder.Length = 0 Then
			WinUtil.DispMessageBox("Setting OutputFolder Property", WinUtil.MessageBoxType.CriticalOK, String.Empty)
			Me.PropertyGrid1.Focus()
			Exit Sub
		End If
		If Me.txtClassName.Text.Length = 0 Then
			WinUtil.DispMessageBox("Input Class Name", WinUtil.MessageBoxType.CriticalOK, String.Empty)
			Me.txtClassName.Focus()
			Exit Sub
		End If
		If Me.chkDifinition.Checked Then
            If Me.txtTableName.Text.Length = 0 Then
                WinUtil.DispMessageBox("Input TableName Name", WinUtil.MessageBoxType.CriticalOK, String.Empty)
                Me.txtTableName.Focus()
                Exit Sub
            End If
        End If

		Dim dt As DataTable

		dt = Me.DataGridView2.DataSource

		Dim gen As EntityCodeGenerator
		gen = New EntityCodeGenerator
		gen.Namespace = _dbc.TargetNamespace
        gen.ClassName = Me.txtClassName.Text
        gen.Language = _dbc.Language
		gen.AutoImplementedProperties = _dbc.AutoImplementedProperties
		gen.INotifyPropertyChangedBase = _dbc.INotifyPropertyChangedBase
        gen.TableProperty = Me.chkTable.Checked
		If Me.chkDifinition.Checked Then
			gen.TableName = Me.txtTableName.Text
			gen.Generate(_dt.Columns, dt.Rows)
		Else
			gen.Generate(_dt.Columns)
		End If

		Dim filename As String
		filename = gen.Write(_dbc.OutputFolder)
		exec(filename)
	End Sub

	Private Sub exec(ByVal filename As String)
		Dim exeInfo As ProcessStartInfo
		Dim process As Process

		Try
			exeInfo = New ProcessStartInfo()
			exeInfo.FileName = filename

			process = System.Diagnostics.Process.Start(exeInfo)

			If process.HasExited Then
				Exit Sub
			End If
		Catch ex As Exception
			Debug.Print(ex.Message)
		End Try
	End Sub

	Private Sub cboConnectionStrings_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles cboConnectionStrings.SelectedIndexChanged
		_dbc = Nothing

		If Me.cboConnectionStrings.SelectedIndex < 0 Then
			Exit Sub
		End If

		_dbc = My.MySettings.Default.DbContext(Me.cboConnectionStrings.SelectedIndex)

		Me.PropertyGrid1.SelectedObject = _dbc
	End Sub

    Private Sub chkDifinition_CheckedChanged(sender As Object, e As EventArgs) Handles chkDifinition.CheckedChanged
        Me.chkTable.Visible = Me.chkDifinition.Checked
        Me.Label3.Visible = Me.chkDifinition.Checked
        Me.txtTableName.Visible = Me.chkDifinition.Checked
        Me.DataGridView2.Visible = Me.chkDifinition.Checked
    End Sub
End Class
